<template>
  <div class="video">
    <el-card>
      <div slot="header">
        <h3 style="padding:0;margin:0 5px">课程:{{$route.query.sectionName}}</h3><br />
        <h3 style="padding:0;margin:0 5px">课时:{{$route.query.theme}}</h3><br />
      </div>

      <el-form label-position="left" label-width="80px">
        <el-form-item label="视频上传">
          <input class="inputclass" ref="video-file" type="file" />
        </el-form-item>

        <el-form-item label="封面上传">
          <input ref="image-file" type="file" />
        </el-form-item>

        <el-form-item>
          <el-button size="small">取消</el-button>
          <el-button type="primary" @click="onSaveLesson" size="small">开始上传</el-button>
        </el-form-item>
      </el-form>
      <span v-if="isPercentage">上传进度：</span><el-progress  v-if="isPercentage" :percentage="percentage" :format="format"></el-progress>
      <span v-if="percentage===100">解码进度：</span><el-progress  v-if="percentage===100" :percentage="transCodePercent" :format="format"></el-progress>
    </el-card>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import {
  aliyunImagUploadAddressAdnAuth,
  aliyunVideoUploadAddressAdnAuth,
  aliyunTransCodePercent,
  aliyunTransCode
} from '@/service/aliyun-upload'
export default Vue.extend({
  name: 'video',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      uploader: null,
      imageURL: '',
      videoId: '',
      uploadPercent: '',
      isUploadSuccess: false,
      isTransCodeSuccess: false,
      percentage: 1,
      isPercentage: false,
      transCodePercent: 0

    }
  },
  created () {
    this.initUploader()
  },

  methods: {
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async (uploadInfo: any) => {
          this.isPercentage = true
          console.log('onUploadstarted', uploadInfo)
          // 通过我们的后端获取文件上传凭证
          let uploadAddressAndAuth
          if (uploadInfo.isImage) {
            // 获取图片上传凭证
            const { data } = await aliyunImagUploadAddressAdnAuth()
            this.imageURL = data.data.imageURL
            uploadAddressAndAuth = data.data
            console.log('img', data)
          } else {
            // 获取视频上传凭证
            const { data } = await aliyunVideoUploadAddressAdnAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageURL
            })
            uploadAddressAndAuth = data.data
            console.log('video', data)
            this.videoId = uploadAddressAndAuth.videoId
          }

          // 调用setUploadAuthAndAddress(uploadInfo, accessKeyId, accessKeySecret, secretToken);设置上传凭证
          (this.uploader as any).setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAndAuth.uploadAuth,
            uploadAddressAndAuth.uploadAddress,
            uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
          )
          // 设置好上传凭证，确认没有问题，上传进度开始
          ;(this.uploader as any).startUpload()
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo: any) {
          console.log('onUploadSucceed', uploadInfo)
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo: any, code: any, message: any) {
          console.log('onUploadFailed', uploadInfo)
          console.log(code)
          console.log(message)
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (
          uploadInfo: any,
          totalSize: any,
          loadedPercent: any
        ) => {
          console.log('onUploadProgress', uploadInfo)
          console.log(totalSize)
          console.log(loadedPercent)
          if (!uploadInfo.isImage) {
            this.percentage = loadedPercent * 100
          }
        },
        // 上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo: any) {
          console.log('onUploadTokenExpired', uploadInfo)
        },
        // 全部文件上传结束
        onUploadEnd: async () => {
          console.log('请求转码')
          const { data } = await aliyunTransCode({
            lessonId: this.$route.query.lessonId,
            coverImageURL: this.imageURL,
            fileName: (this.$refs['video-file'] as any).files[0].name,
            fileId: this.videoId
          })
          console.log(data)
          console.log('查询进度')
          const timer = setInterval(async () => {
            const { data: result } = await aliyunTransCodePercent(
              this.$route.query.lessonId as string
            )
            console.log(result.data)
            this.transCodePercent = result.data
            if (result.data === 100) {
              console.log('转码成功')
              window.clearInterval(timer)
            }
          }, 1000)
        }
      })
    },
    onSaveLesson () {
      // 获取上传的文件
      this.percentage = 0
      const upload = this.uploader as any
      const videoFile = (this.$refs['video-file'] as any).files[0]
      const imageFile = (this.$refs['image-file'] as any).files[0]
      var paramData = '{"Vod":{}}'
      // 添加文件列表
      // 当开始上传时，他就会按照列表顺序上传，并不是并行上传
      upload.addFile(imageFile, null, null, null, paramData)
      upload.addFile(videoFile, null, null, null, paramData)
      // 开始上传
      upload.startUpload()
    },
    format (percentage:any) {
      return percentage === 100 ? '已完成' : `${percentage}%`
    }

  }
})
</script>
<style lang="scss" scoped>

</style>
